#!/usr/bin/env node
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _glob = require('glob');

var _glob2 = _interopRequireDefault(_glob);

var _child_process = require('child_process');

var _utils = require('./utils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }

// const program = require('commander')

// program
//   .version(require('../package').version, '-v, --version')
//   .option('--verbose', 'Print a
// formatted string of the compilation information (similar to CLI output).')
//   .parse(process.argv)

// require('../lib/build')(program)

var _process$argv = _toArray(process.argv),
    executor = _process$argv[0],
    bin = _process$argv[1],
    script = _process$argv[2],
    args = _process$argv.slice(3);

function getEnv() {
  return Object.keys(process.env).filter(function (key) {
    return process.env[key] !== undefined;
  }).reduce(function (envAcc, key) {
    return _extends({}, envAcc, _defineProperty({}, key, process.env[key]));
  }, {});
}

function spawnSyncScript() {
  var relativeScriptPath = _path2.default.join(__dirname, './scripts', script);
  var scriptPath = require.resolve(relativeScriptPath);

  if (!scriptPath) {
    throw new Error('Unknown script "' + script + '".');
  }

  var result = (0, _child_process.spawnSync)(executor, [scriptPath].concat(_toConsumableArray(args)), {
    stdio: 'inherit',
    env: getEnv()
  });

  if (result.signal) {
    process.exit(1);
  } else {
    process.exit(result.status);
  }
}

if (!script) {
  var scriptsPath = _path2.default.join(__dirname, 'scripts/');
  var scriptsAvailable = _glob2.default.sync(_path2.default.join(__dirname, 'scripts', '*'));
  var scriptsAvailableMessage = scriptsAvailable.map(function (s) {
    return s.replace(scriptsPath, '').replace(/\.js$/, '');
  }).join('\n  ').trim();

  var fullMessage = ('\nUsage: ' + bin + ' [script] [--options]\nAvailable Scripts:\n  ' + scriptsAvailableMessage + '\n  ').trim();
  console.log('\n' + fullMessage + '\n'); // eslint-disable-line
} else {
  spawnSyncScript();
}

process.on('unhandledRejection', function (error) {
  _utils.logger.error('unhandledRejection', error.message);
});